#include "epoll.h"
// 初始化
int tcp_server_init(const char *ip, int port, int backlog)
{
    int fd = socket(PF_INET, SOCK_STREAM, 0);
    if (-1 == fd)
        return fd;
    struct sockaddr_in saddr;
    saddr.sin_family = PF_INET;
    saddr.sin_port = htons(port);
    saddr.sin_addr.s_addr = inet_addr(ip);
    int ok = 1;
    if (-1 == setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &ok, sizeof ok))
    {
        perror("setsockopt");
        return -1;
    }

    if (-1 == bind(fd, (void *)&saddr, sizeof saddr))
        return -1;

    if (-1 == listen(fd, backlog))
        return -1;
    puts("listen...");
    return fd;
}
// 等待连接
int tcp_server_wait(int listenfd)
{
    struct sockaddr_in caddr; // 用来存储连接的客户端的IP PORT
    socklen_t len = sizeof caddr;

    int nfd = accept(listenfd, (void *)&caddr, &len);
    if (-1 == nfd)
        return -1;
    printf("Client %s:%d connected!\n", inet_ntoa(caddr.sin_addr), ntohs(caddr.sin_port));
    return nfd;
}
int  sendfile(int nfd)
{
    char buf[1024],name[32];
   if (0 >= recv(nfd, buf, 1024, 0))
                {
                    return -1;
                }
    if (0 != strncmp(buf,"download",8))
    {
        return 0;
    }
    sprintf(name,"%s",buf+9);
    puts(name);
    int fd = open(name,O_RDONLY);
    if (-1 == fd)
    {
        sprintf(buf,"NO");
        send(nfd,buf,1024,0);
        return -1;
    }
    sprintf(buf,"OK");
    write(nfd,buf,1024);
    int ret ;
    while (1)
    {
        ret =read(fd,buf,1024);
        printf("%d\n",ret);
        send(nfd,&ret,4,MSG_NOSIGNAL);
        send(nfd,buf,ret,0);
        if (0 == ret)
        {
            break;
        }  
    }
    
}